import React,{useState,useEffect} from 'react'
import {Input,Button,Space, message}from 'antd'
import {useNavigate,redirect}from 'react-router-dom'
import baseurl from '../../axios/config'

export default function Login() {
    
    const  navigate= useNavigate()
    const [un ,setun]= useState("")
    const [pw ,setpw]= useState("")
    const a=(e:any)=>{
  setun(e.target.value)
  console.log(e.target.value)
    }
    const b= (e:any)=>{
      setpw(e.target.value)
      console.log(e.target.value)
      console.log(e)
    }
    const tj=()=>{
        baseurl.post("/lg",{
            name: un,
            password:pw
        }).then(res=>{
            console.log(res.data.id)
            const lid = res.data.id
            switch(lid){
                case "登录成功":
                return (  
                      localStorage.setItem("token",res.data.token), navigate('/home'
                         
                   ), localStorage.setItem("xiaolu",un)
                         
                );
                case "用户名不对":
                    return( window.alert("用户名不对"),location.reload(), redirect('/'), setun(""));
                    case "密码不对":
                        return( window.alert("密码不对"),location.reload(), redirect('/'), setpw(""));
            }
        })
        
    }
    const reg=()=>{
     navigate('/reg')
    }
    useEffect(()=>{
     const token = localStorage.getItem("token")
     if(token){
        navigate('/home')
     } 
    })
  return (
    <div>
        <h1>pi业主登录</h1>
    用户名<Input style={{ width: 304 }}   name="name"  value={un} onChange={a} /><br></br>
     密码<Input.Password  style={{ width: 304 }}  name="password"  value={pw} onChange={b} /><br></br>
     <Space>
     <Button type="primary" onClick={tj}>登录</Button><br></br>
     <Button type="primary" onClick={reg}>注册</Button></Space>
     </div>
  )
}
